import * as React from 'react';
import styles from './index.less';
import loginBg from '../../images/bj.png';
import loginLogo from '../../images/logo.png';
import { Form, Input, Row, Col, Button, Radio, message } from 'antd';
import {
  TeamOutlined,
  IdcardOutlined,
  CodepenOutlined,
} from '@ant-design/icons';
import request from '../../http';
import { history, Link } from 'umi';
import adminService from '@/api/admin/api';
import { RequestResult } from '@/api/admin/api';

const layout = {
  labelCol: { span: 0 },
  wrapperCol: { span: 24 },
};

export default () => {
  const [formObject] = Form.useForm();
  const [captchaUrl, setCaptchaUrl] = React.useState('');

  const updateCaptcha = async () => {
    const t = new Date().getMilliseconds();
    let captchaNo;
    if (t < 10) {
      captchaNo = '000' + t;
    } else if (t >= 10 && t < 100) {
      captchaNo = '00' + t;
    } else if (t >= 100 && t < 1000) {
      captchaNo = '0' + t;
    }
    let resultForImage = await request
      .get('captcha?captchaNo=' + captchaNo, {
        responseType: 'arraybuffer',
      })
      .then((response: any) => {
        return (
          'data:image/png;base64,' +
          btoa(
            new Uint8Array(response).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              '',
            ),
          )
        );
      });
    setCaptchaUrl(resultForImage);
  };

  React.useEffect(() => {
    updateCaptcha().then();
  }, []);

  const doLogin = async () => {
    const data = await formObject.validateFields();
    alert(JSON.stringify(data));
    alert('登录成功开始跳转');
    const result: any = await request.post('/user/login', data, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    });
    /*const result: any = {
      success:true,
      message:'用户名密码错误',
    };*/
    // const result2: RequestResult = await adminService.doLogin(data);
    // console.log(result2);
    if (result.success) {
      if (data.userType === 'student') {
        history.push('/student');
      } else if (data.userType === 'teacher') {
        history.push('/teacher');
      } else {
        history.push('/');
      }
      window.localStorage.setItem('token', '123456');
    } else {
      message.error(result.message);
    }
  };

  return (
    <div className={styles.loginMain}>
      <img src={loginBg} className={styles.loginBg} />
      <div className={styles.loginContent}>
        <div className={styles.loginLogo}>
          <img src={loginLogo} />
        </div>
        <p className={styles.loginTitle}>学生实训考勤管理系统</p>
        <div className={styles.loginForm}>
          <Form {...layout} name="loginForm" form={formObject} preserve={false}>
            <Form.Item
              name="userNo"
              label={'账号'}
              rules={[
                { required: true, whitespace: true, message: '账户不能为空!' },
                { max: 30, message: '最大长度不能超过30!' },
              ]}
            >
              <Input prefix={<TeamOutlined />} placeholder="账户" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                { required: true, whitespace: true, message: '密码不能为空!' },
                { max: 30, message: '最大长度不能超过30!' },
              ]}
              style={{ marginBottom: 24 }}
            >
              <Input.Password prefix={<IdcardOutlined />} placeholder="密码" />
            </Form.Item>
            <Form.Item
              name="captcha"
              rules={[
                {
                  required: true,
                  whitespace: true,
                  message: '验证码不能为空!',
                },
                { max: 30, message: '最大长度不能超过30!' },
              ]}
              style={{ marginBottom: 24 }}
            >
              <Row gutter={8}>
                <Col span={17}>
                  <Input prefix={<CodepenOutlined />} placeholder="验证码" />
                </Col>
                <Col span={5}>
                  <img
                    className={styles.captchaImg}
                    src={captchaUrl}
                    onClick={updateCaptcha}
                  />
                </Col>
              </Row>
            </Form.Item>
            <Form.Item
              name="userType"
              rules={[
                {
                  required: true,
                  whitespace: true,
                  message: '用户类型不能为空!',
                },
                { max: 30, message: '最大长度不能超过30!' },
              ]}
              style={{ marginBottom: 24 }}
              initialValue="student"
            >
              <Radio.Group>
                <Radio value="student">学生</Radio>
                <Radio value="teacher">老师</Radio>
                <Radio value="admin">管理员</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item style={{ marginBottom: 24 }} initialValue="student">
              <Row gutter={8}>
                <Col span={17}>
                  <Button
                    type={'primary'}
                    style={{ width: '100%' }}
                    onClick={doLogin}
                  >
                    登录
                  </Button>
                </Col>
                <Col span={5}>
                  <Link to={{ pathname: '/userManager', state: { id: 1 } }}>
                    用户管理
                  </Link>
                  <Button type={'link'}>忘记密码</Button>
                </Col>
              </Row>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};
